package com.hezhi.trafficcopsys.view.action;

import java.io.IOException;
import java.util.Enumeration;

import com.hezhi.framework.Constants;
import com.hezhi.framework.action.BaseAction;
import com.hezhi.framework.exception.APPException;
import com.hezhi.trafficcopsys.domain.User;
import com.hezhi.trafficcopsys.service.UserService;
import com.hezhi.trafficcopsys.service.impl.UserServiceImpl;

/**
 * 
 * @author  : Tony
 * @version : 1.00
 * Create Time : 2011-7-16-下午01:36:43
 * Description : 
 *             登录Action 
 * History：
 *  Editor       version      Time               Operation    Description*
 *  
 *
 */
public class LoginAction extends BaseAction{
	
	private static final long serialVersionUID = -8263264432046589057L;
	
	//注入Service
	private UserService userService;
	
	public LoginAction(){
		userService = new UserServiceImpl();
	}

	//form bean
	private User user;

	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
	
	/**
	 * Function  : 
	 * @author   : Tony
	 */
	public void doCheckUser() throws IOException {
		try {
			if (!userService.isExistedUser(user.getUsername())) {
				response.setCharacterEncoding(Constants.ENCODING_UTF8);
				response.getWriter().print("0");
			}
		} catch (APPException e) {
			response.setCharacterEncoding(Constants.ENCODING_UTF8);
			response.getWriter().print(e.getMessage());
		}
	}
	
	/**
	 * author  : Tony
	 * about version ：1.00
	 * create time   : 2011-7-16-下午01:37:09
	 * Description ：登录操作
	 * @throws IOException 
	 */
	public void doLogin() throws IOException {
		try{
			User dbUser = userService.doLogin(user);
			if( dbUser !=null ){
				//否则保存帐号信息到session中
				session.setAttribute(Constants.SESSION_LOGIN, dbUser);
			}
		} catch ( APPException e){
			response.setCharacterEncoding(Constants.ENCODING_UTF8);
			response.getWriter().print(e.getMessage());
		}
	}
	
	/**
	 * Function  : 注销操作
	 * @author   : Tony
	 */
	public String doLogout(){
		Enumeration<?> enums = session.getAttributeNames();
		while(enums.hasMoreElements()){
			session.removeAttribute(enums.nextElement().toString());
		}
		return SUCCESS;
	}
}
